<?php
/**
 * Talents come from diligence, and knowledge is gained by accumulation.
 *
 * @author: 晋<657306123@qq.com>
 */

namespace app;

use think\db\exception\ModelNotFoundException;
use think\facade\Config;
use think\Loader;

trait NotFoundModelExceptionHandle{

	/**
	 * 获取模型或Query实例消息
	 *
	 * @param \think\db\exception\DataNotFoundException|\think\db\exception\ModelNotFoundException $e
	 * @return string
	 */
	protected function resolveModelErrorMessage($e){
		$name = $this->resolveModelOrTableName($e);
		$titleMap = $this->getModelTitleMap();
		return isset($titleMap[$name]) ? $titleMap[$name].'不存在' : '数据不存在';
	}

	/**
	 * @return array
	 */
	private function getModelTitleMap(){
		return [
			'post'     => '文章',
			'category' => '专题',
		];
	}

	/**
	 * @param mixed $e
	 * @return false|string
	 */
	private function resolveModelOrTableName($e){
		if($e instanceof ModelNotFoundException){
			$name = basename(str_replace("\\", "/", $e->getModel()));
			$name = Loader::parseName($name, 0);
		}else{
			$name = $e->getTable();
		}

		$prefix = Config::get('database.prefix');
		if(stripos($name, $prefix) === 0){
			$name = substr($name, strlen($prefix));
		}

		return $name;
	}
}
